package com.example.siyun.controller.logincontroller;
import com.example.siyun.pojo.*;
import com.example.siyun.service.impl.shouyeserviceimpl.LoginlogServiceImpl;
import com.example.siyun.service.loginservice.UserService;
import com.example.siyun.service.userserver.UserDeveService;
import com.example.siyun.util.IpUtils;
import com.example.siyun.util.JsonResult;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
 * @Auther: 全
 * @Date: 2022/9/26 09:33
 * @Description: 登录用户的控制成
 */
@RestController
@Slf4j
public class UserController extends BaseController {

    @Autowired
    private DefaultKaptcha captchaProducer;

    @Autowired
    private UserService userService;
    @Autowired
    private LoginlogServiceImpl loginlogService;

    @Autowired
    private UserDeveService userDeveServer;

    /**
     *     /验证码
     */
    @RequestMapping("/kaptcha")
    public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response)throws Exception{
        log.info("获取验证码");
        HttpSession session = request.getSession();
        response.setDateHeader("Expires",0);
        response.setHeader("Cache-Control","no-store,no-cache,must-revalidate");
        response.addHeader("Cache-Control","post-check=0,pre-check=0");
        response.setHeader("Pragma","no-cache");
        response.setContentType("image/jpeg");
/**
 * /        生成验证码
 * //        验证码文字存入Session中
 * //        向客户端写出
 * //        注意   jpg
 */
        String capText = captchaProducer.createText();
        System.out.println(capText);
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY,capText);
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi,"jpg",out);
        try{
            out.flush();
        }finally {
            out.close();
        }
    }
/**
 *    /        用户注册
 */

    @RequestMapping("/users/reg")
    public JsonResult<Void> red(Userr userr){

        UserList list = new UserList();
        list.setUserAccount(userr.getUsername());
        list.setIdCard(userr.getIdCard());
        list.setPhone(userr.getPhone());
        list.setUserEmail(userr.getEmail());
        list.setStu_id(userr.getStu_id());
        list.setCreateDate(new Date());

        userService.reg(userr,list);

        return new JsonResult<>(OK);
    }
/**
 * /    账号密码登录
 */

    @RequestMapping("/goLogin")
    public JsonResult<Userr> redd(String captcha, HttpServletRequest request, HttpServletResponse response, String username, HttpSession session) throws UnknownHostException {
        log.info("账号密码登录");
        InetAddress addr = InetAddress.getLocalHost();
        String ip=addr.getHostAddress();
        String address=addr.getHostName();
        String Address= IpUtils.getIpAddress(request);
        String ipSource = IpUtils.getIpSource(Address);
        Loginlog log=new Loginlog();
        JsonResult<Userr> result=new JsonResult<>();
        Userr userr =userService.login(username);
//        验证码
        String scaptcha = (String)session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        if(!captcha.equals(scaptcha)){
            result.setState(301);
            result.setMessage("验证码错误");
            return result;
        }
        if(userr !=null){
            int id= userr.getUid();
            session.setAttribute("loginname", userr.getUsername());
            Date aa=new Date();
            Loginlog logg=new Loginlog();
            logg.setLoginDate(aa);
            logg.setLoginIp(ip);
            logg.setLoginState(0);
            logg.setUserId(id);
            logg.setLoginLocation(address);
            BackofficeTable fingbackofficetale = userService.fingbackofficetale(userr.getUsername(), EnumPojo.VALUE_DEL_0);
            if(fingbackofficetale!=null){
                logg.setLoginType(0);
            }else{
                logg.setLoginType(1);
            }
            logg.setLoginname(userr.getUsername());
            loginlogService.insertLog(logg);
            Map<String,Object> usermap=new HashMap<>();
            usermap.put("username", userr.getUsername());
            usermap.put("id", userr.getUid());
            result.setState(200);
            result.setMessage("用户登录成功");
            result.setData(userr);
        }else{
            int id= userr.getUid();
            Date aa=new Date();
            Loginlog logg=new Loginlog();
            logg.setLoginDate(aa);
            logg.setLoginIp(ip);
            logg.setUserId(id);
            logg.setLoginState(2);
            logg.setLoginLocation(address);
            logg.setLoginState(1);
            logg.setLoginType(1);
            loginlogService.insertLog(logg);
            result.setState(300);
            result.setMessage("用户名不存在");
        }
        return result;
    }
    @RequestMapping("/getPhoneKaptcha")
    public void getPhoneKaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        log.info("获取手机号登录的验证码");
        HttpSession session = request.getSession();
        response.setDateHeader("Expires",0);
        response.setHeader("Cache-Control","no-store,no-cache,must-revalidate");
        response.addHeader("Cache-Control","post-check=0,pre-check=0");
        response.setHeader("Pragma","no-cache");
        response.setContentType("image/jpeg");
//        生成验证码
        String capText = captchaProducer.createText();
        System.out.println(capText);
//        验证码文字存入Session中
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY,capText);
        System.out.println("手机验证码是："+capText);
        log.info("获取的验证码是"+capText);
    }

    @RequestMapping("/users/phoneLogin")
    public JsonResult<Userr> phoneLogin(String captcha, HttpServletRequest request, String phone, HttpSession session) throws UnknownHostException {
        log.info("手机号登录");
//        System.out.println(phone);
        InetAddress addr = InetAddress.getLocalHost();
        /**
         * //获得本机IP
         * //获得本机名称
         */
        String ip=addr.getHostAddress();
        String address=addr.getHostName();
        String Address= IpUtils.getIpAddress(request);
        String ipSource = IpUtils.getIpSource(Address);
        System.out.println(ip+"   "+address+"   "+Address+"  "+ipSource);
        Loginlog log=new Loginlog();
        JsonResult<Userr> result = new JsonResult<>();
        Userr userr = userService.phonelogin(phone);
        System.out.println(userr);
        /**
         * //手机号验证码获取
         */
        String scaptcha = (String)session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        if (!captcha.equals(scaptcha)){
            result.setState(301);
            result.setMessage("验证码错误");
            return result;
        }
        if (userr != null){
            int uid = userr.getUid();
            session.setAttribute("loginname", userr.getUsername());
            Date aa=new Date();
            Loginlog logg=new Loginlog();
            logg.setLoginDate(aa);
            logg.setLoginIp(ip);
            logg.setLoginState(0);
            logg.setUserId(uid);
            logg.setLoginLocation(address);
            logg.setLoginType(1);
/**
 *  /            添加登录信息
 */
            loginlogService.insertLog(logg);
            Map<String,Object> usermap=new HashMap<>();
            usermap.put("username", userr.getUsername());
            usermap.put("id", userr.getUid());

            result.setState(200);
            result.setMessage("登录成功");
            result.setData(userr);
        }else{
            int id= userr.getUid();
            Date aa=new Date();
            Loginlog logg=new Loginlog();
            logg.setLoginDate(aa);
            logg.setLoginIp(ip);
            logg.setUserId(id);
            logg.setLoginState(2);
            logg.setLoginLocation(address);
            logg.setLoginState(1);
            logg.setLoginType(1);
            loginlogService.insertLog(logg);
            result.setState(300);
            result.setMessage("用户名不存在");
        }
        return result;
    }

    /**
     * 退出登录
     *
//     * @param session
     * @return
     */

    @RequestMapping("/user/loginOut")
    public Map<String,Object> loginOut(HttpSession session) {
        session.removeAttribute("loginname");
        Map<String, Object> map = new HashMap<>();
        map.put("msg","退出成功");
        return map;
    }

//    @RequestMapping(value = "/addRoleJob",method = RequestMethod.POST,headers = "Accept=application/json")
//    public HttpResponseEntity addRoleJob(@RequestBody UserList userList){
//        HttpResponseEntity httpResponseEntity = new HttpResponseEntity ();
//        try{
//            int addRoleJob = roleService.addRoleJob(role);
//            httpResponseEntity.setData ( addRoleJob );
//            httpResponseEntity.setCode ( Constans.SUCCESS_CODE );
//            httpResponseEntity.setMessage(Constans.ADD_SUCCESS_MESSAGE);
//        }catch (Exception e){
//            httpResponseEntity.setCode ( Constans.ADD_EXIST_CODE );
//            httpResponseEntity.setMessage ( Constans.ADD_EXIST_MESSAGE );
//        }
//        return httpResponseEntity;
//    }

}

